﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Xml.Linq;
using HZ.Public;
using Newtonsoft.Json;

namespace HZ.PublicDispatch
{
    public class DC_INFO
    {     
        public List<object> DataList { get; set; }
    }
    public class Msg10001
    {
        public string FACTORY_ID { get; set; }  //工厂，可配置(定义)
        public string LINE_ID { get; set; }     //生产线，工厂下的某条生产线，可配置(定义)
        public string WORK_ID { get; set; }     //工序，生产线下的某个工序，可配置(定义)
        public string RESOURCECODE { get; set; }//资源编号，某个工序下的生产资源，可配置(定义)
        public string DEIVCECODE { get; set; }  //设备编号，生产资源下的某个设备，可配置(定义)
        public string CARRIER_ID { get; set; }  //载具编号
        public string CABINET_ID { get; set; }    //柜号
        public string SN { get; set; }          //电芯条码
        public string SEND_TIME { get; set; }   //同步时间，格式：”2021-06-05 14:22:45”
        public string WORK_NO { get; set; }     //操作员工号
    }
    public class Msg10002
    {
        public string FACTORY_ID { get; set; }  //工厂，可配置(定义)
        public string LINE_ID { get; set; }     //生产线，工厂下的某条生产线，可配置(定义)
        public string WORK_ID { get; set; }     //工序，生产线下的某个工序，可配置(定义)
        public string RESOURCECODE { get; set; }//资源编号，某个工序下的生产资源，可配置(定义)
        public string DEIVCECODE { get; set; }  //设备编号，生产资源下的某个设备，可配置(定义)
        public string CARRIER_ID { get; set; }  //载具编号
        public string LOCATION { get; set; }    //所在位置
        public string SN { get; set; }          //电芯条码
        public string WORK_NO { get; set; }     //操作员工号
        public string PRODUCT_NUMBER { get; set; }//产品数量
        public string STATUS { get; set; }      //生产结果OK：合格 NG：不合格
        public string FILEPATH { get; set; }
        public List<object> DC_INFO { get; set; }     //收集的信息
        public string SEND_TIME { get; set; }   //同步时间，格式：”2021-06-05 14:22:45”
        public string COLL_TIME { get; set; }   //采集时间，格式：”2021-06-05 14:22:45”
    }

    public class Msg10003
    {
        public string FACTORY_ID { get; set; }      //工厂，可配置(定义)
        public string LINE_ID { get; set; }         //生产线，工厂下的某条生产线，可配置(定义)
        public string WORK_ID { get; set; }         //工序，生产线下的某个工序，可配置(定义)
        public string RESOURCECODE { get; set; }    //资源编号，某个工序下的生产资源，可配置(定义)
        public string DEIVCECODE { get; set; }      //设备编号，生产资源下的某个设备，可配置(定义)
        public string CARRIER_ID { get; set; }      //载具编号
        public string SN { get; set; }              //电芯条码
        public string WORK_NO { get; set; }         //操作员工号
        public string SEND_TIME { get; set; }       //同步时间，格式：”2021-06-05 14:22:45”
        public string FILENAME { get; set; }        //文件名称
    }

    public class CallMESClass
    {
        //public static string url = ConfigurationManager.AppSettings["url"];      

        public static Dictionary<string, string> JsonToDictionary(string jsonData)
        {
            //实例化JavaScriptSerializer类的新实例
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
                return jss.Deserialize<Dictionary<string, string>>(jsonData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static string UploadFile(Msg10003 msg, string localFile)
        {

            string url = ConfigurationManager.AppSettings["MSG10003"].ToString();
            Msg10003 body = new Msg10003();
            body = msg;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic = JsonToDictionary(JsonConvert.SerializeObject(msg));
            foreach (var pair in dic)
            {
                url += string.Format("&{0}={1}", pair.Key, pair.Value);
            }
            return UploadRequest(url, localFile, dic);

        }

        public static string UploadParams(Msg10002 msg)
        {
            string url = ConfigurationManager.AppSettings["MSG10002"].ToString();

            Msg10002 body = new Msg10002();
            //body.DC_INFO = new DcInfo();
            body = msg;
            string postData = JsonConvert.SerializeObject(body);
            return PostUrl(url, postData);

        }

        public static string PostUrl(string url, string postData)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.Timeout = 2000;//设置请求超时时间，单位为毫秒
            req.ContentType = "application/json";
            req.ServicePoint.Expect100Continue = false;
            byte[] data = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = data.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            //获取响应内容
            string result = "";
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }


        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }


        /// <summary>
        /// 上传文件请求
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="formDatas">表单数据（字典格式）</param>
        /// <param name="callback">上传回调</param>
        public static string UploadRequest(string url, string filePath, Dictionary<string, string> formDatas)
        {
            string returnValue = "";
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
            // 时间戳，用做boundary
            string timeStamp = DateTime.Now.Ticks.ToString("x");

            //根据uri创建HttpWebRequest对象
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
            httpReq.Method = "POST";
            httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
            httpReq.ServicePoint.Expect100Continue = false;
            httpReq.Timeout = 300000; //设置获得响应的超时时间（300秒）
            httpReq.ContentType = "multipart/form-data; boundary=" + timeStamp;

            //读取file文件
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader binaryReader = new BinaryReader(fileStream);

            //表单信息
            string boundary = "--" + timeStamp;
            string form = "";
            //string formFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
            //string formEnd = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type:application/octet-stream\r\n\r\n";
            //foreach (var pair in formDatas)
            //{
            //    form += string.Format(formFormat, pair.Key, pair.Value);
            //}
            //form += string.Format(formEnd, "file", Path.GetFileName(filePath));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(form);

            //结束边界
            byte[] boundaryBytes = Encoding.ASCII.GetBytes(/*"\r\n--" + timeStamp + "--\r\n"*/"");
            long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
            httpReq.ContentLength = length; //请求内容长度

            try
            {
                //每次上传4k
                int bufferLength = 4096;
                byte[] buffer = new byte[bufferLength];

                //已上传的字节数
                long offset = 0;
                int size = binaryReader.Read(buffer, 0, bufferLength);
                Stream postStream = httpReq.GetRequestStream();

                //发送请求头部消息
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

                while (size > 0)
                {
                    postStream.Write(buffer, 0, size);
                    offset += size;
                    size = binaryReader.Read(buffer, 0, bufferLength);
                }

                //添加尾部边界
                postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                postStream.Close();

                //获取服务器端的响应
                using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse())
                {
                    Stream receiveStream = response.GetResponseStream();
                    StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                    returnValue = readStream.ReadToEnd();
                    Console.Write("upload result:" + returnValue);
                    //callback?.Invoke(returnValue);

                    response.Close();
                    readStream.Close();
                }
            }
            catch (Exception ex)
            {
                Console.Write("文件传输异常： " + ex.Message);
                //callback?.Invoke(ex.Message);
                returnValue = ex.Message;
            }
            finally
            {
                fileStream.Close();
                binaryReader.Close();
            }
            return returnValue;
        }

        /// <summary>
        /// CSV文件数据筛选后另存文件
        /// </summary>
        public static void CSVTest(string strDataFilePath)
        {
            DirectoryInfo di = new DirectoryInfo(@"D:\Test");
            if (!di.Exists)//如果文件目录不存在，创建该目录
            {
                di.Create();
            }
            FileInfo fi = new FileInfo(strDataFilePath);
            string newDataFilePath = di.FullName + "\\" + fi.Name;
            if (!File.Exists(newDataFilePath))//如果文件不存在则新建
            {
                File.CreateText(newDataFilePath);
            }
            using (StreamReader sr = File.OpenText(strDataFilePath))
            {
                while (!sr.EndOfStream)
                {
                    string lineData = sr.ReadLine();
                    string[] strdatas = lineData.Split(',');
                    if (strdatas.Length > 2)
                    {
                        if (strdatas[2] != "0" && strdatas[15] != "0")//过滤工步时间为0和工步类型为0的两种数据
                        {
                            List<string> appendline = new List<string>
                            {
                                lineData
                            };
                            File.AppendAllLines(newDataFilePath, appendline, Encoding.UTF8);
                        }
                    }
                }
            }
        }
    }
}
